package com.tcp;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import com.domain.CarDevice;
import com.util.JDBCUtil;

public class Sql {
    public static String select(String device,Connection conn){
        String device1="";
        try {
            String sql="SELECT device FROM car_elements WHERE device = ?";
            PreparedStatement ps=conn.prepareStatement(sql);
            ps.setString(1,device);
            ResultSet rs=ps.executeQuery();
            while (rs.next()){
                device1=rs.getString("device");
            }
            JDBCUtil.closeResourse(rs,ps,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return device1;
    }
    public static int insert(CarDevice carDevice, Connection conn){
        int n=0;
        try {
            String sql="INSERT INTO car_elements (element,device,Akilometers,Ukilometers,genuine,cartridgelife) VALUES('空气滤芯',?,'0',?,'真',?)";
            PreparedStatement ps=conn.prepareStatement(sql);
            ps.setString(1,carDevice.getDevice());
            ps.setString(2,carDevice.getKilometers());
            ps.setString(3,carDevice.getAp());
            n=ps.executeUpdate();
            JDBCUtil.closeResourse(null,ps,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return n;
    }
    public static int update(CarDevice carDevice,Connection conn){
        int n=0;
        String Akilometers=selectAkilometers(carDevice.getDevice(),conn);
        int ak=Integer.parseInt(Akilometers);
        ak=ak+15;
        try {
            String sql="UPDATE car_elements SET Ukilometers=?,cartridgelife=?,Akilometers=? WHERE device=?";
            PreparedStatement ps=conn.prepareStatement(sql);
            ps.setString(1,carDevice.getKilometers());
            ps.setString(2,carDevice.getAp());
            ps.setString(3,ak+"");
            ps.setString(4,carDevice.getDevice());
            n=ps.executeUpdate();
            JDBCUtil.closeResourse(null,ps,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return n;
    }
    public static String selectAkilometers(String device,Connection conn){
        String Akilometers="";
        try {
            String sql="SELECT Akilometers FROM car_elements WHERE device = ?";
            PreparedStatement ps=conn.prepareStatement(sql);
            ps.setString(1,device);
            ResultSet rs=ps.executeQuery();
            while (rs.next()){
                Akilometers=rs.getString("Akilometers");
            }
            JDBCUtil.closeResourse(rs,ps,null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Akilometers;
    }
}
